package cn.kgc.Adjudicative.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.kgc.Adjudicative.common.Constants;
import cn.kgc.Adjudicative.common.Result;
import cn.kgc.Adjudicative.entity.DUser;
import cn.kgc.Adjudicative.entity.vo.LoginVO;
import cn.kgc.Adjudicative.exception.ServiceException;
import cn.kgc.Adjudicative.mapper.DUserMapper;
import cn.kgc.Adjudicative.service.DUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author sun
 * @since 2023-01-05
 */
@Service
public class DUserServiceImpl extends ServiceImpl<DUserMapper, DUser> implements DUserService {

    @Resource
    private DUserMapper dUserMapper;

    @Override
    public DUser login(LoginVO loginVO) {
        DUser one = getUserInfo(loginVO);
        if (one!=null) {
            BeanUtil.copyProperties(one,loginVO,true);
            return one;
        }else {
            throw new RuntimeException("用户名或密码错误");
        }
    }

    @Override
    public DUser getUserByUsername(String username) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        DUser user = dUserMapper.selectOne(queryWrapper);
        return user;
    }

    private DUser getUserInfo(LoginVO loginVO){
        QueryWrapper<DUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",loginVO.getUserName());
        queryWrapper.eq("password",loginVO.getPassword());
        DUser one;
        try{
            one = getOne(queryWrapper);//从数据库查询用户信息
        }catch (Exception e) {
            e.printStackTrace();
            // LOG.error(e);
            throw new ServiceException(Constants.CODE_500,"系统错误");
        }
        return one;
    }

    // @Override
    // public Result login(String username, String password, String code, HttpServletRequest request) {
    //     String captcha = (String) request.getSession().getAttribute("captcha");
    //     System.out.println(captcha);
    //     if (StringUtils.isBlank(code) || !captcha.equalsIgnoreCase(code)){
    //         return Result.error(Constants.CODE_400,"验证码输入错误，请重新输入！");
    //     }
    //     return Result.success();
    // }
}
